﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;

namespace _180FrameWork.CustControls
{
    public class TextBoxTraceListener : TraceListener
    {
        private TextBox _target;
        private StringSendDelegate _invokeWrite;
        private int _Length = 5000;
        public int Length { get { return this._Length; } set { this._Length = value; } }

        public TextBoxTraceListener(TextBox target)
        {
            _target = target;
            
            _invokeWrite = new StringSendDelegate(SendString);
        }

        public override void Write(string message)
        {
            _target.Invoke(_invokeWrite, new object[] { message });
        }

        public override void WriteLine(string message)
        {
            _target.Invoke(_invokeWrite, new object[] { message + Environment.NewLine });
        }

        private delegate void StringSendDelegate(string message);
        private void SendString(string message)
        {
            //控制长度
            //if (_target.Lines.Length > Lines)
            //    _target.Text = _target.Text.Remove(0, _target.Text.IndexOf("\r\n") + 2);
            if (_target.Text.Length > Length)
                _target.Text = "";
            _target.Text += message;
            _target.SelectionStart = _target.Text.Length;
            _target.ScrollToCaret();
        }
    }
}
